import os
from django.shortcuts import render, get_object_or_404
from django.views import View
from django.http import JsonResponse
from .models import GuitarTab, GuitarTabImage
from .util import Utils
from django.conf import settings
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger


class UploadFileView(View):

    def post(self, request, *args, **kwargs):
        uploaded_file = request.FILES.get('images')

        if not uploaded_file:
            return JsonResponse({'error': '没有上传文件'}, status=400)

        file_ext = uploaded_file.name.split('.')[-1]
        save_name = f"{Utils.get_uuid()}.{file_ext}"
        save_path = os.path.join(settings.STATICFILES_DIRS[3], save_name)
        with open(save_path, 'wb+') as destination:
            for chunk in uploaded_file.chunks():
                destination.write(chunk)

        return JsonResponse(
            {'message': '上传成功', 'save_path': save_path, 'save_name': save_name,
             'web_path': Utils.get_guitar_url(save_name)},
            status=200)


class DeleteFileView(View):
    def post(self, request):
        # 获取请求中的文件路径
        file_path = request.POST.get('path')
        if file_path:
            # 删除文件
            print(file_path)
            if os.path.exists(file_path):
                os.remove(file_path)
            return JsonResponse({'message': '删除成功'}, status=200)
        else:
            return JsonResponse({'message': '路径无效'}, status=400)


class UploadGuitarTabView(View):

    def get(self, request):
        return render(request, 'guitar/UploadGuitarTab.html')

    def post(self, request):
        name = request.POST.get('name', '')
        author = request.POST.get('author', '')
        type = request.POST.get('type', '')
        cover_path = request.POST.get('cover_path', '')  # 这里 cover_path 应该是通过第一个接口上传的结果

        # 创建 GuitarTab 实例
        guitar_tab = GuitarTab.objects.create(
            name=name,
            author=author,
            type=type,
            cover_path=cover_path
        )

        # 获取所有的文件路径列表
        file_paths = request.POST.getlist('file_paths')  # 预期 file_paths 是保存的 save_path 列表
        print(file_paths)
        for index, file_path in enumerate(file_paths):
            save_name = os.path.basename(file_path)  # 从路径中提取文件名

            # 创建 GuitarTabImage 实例
            GuitarTabImage.objects.create(
                save_path=file_path,
                save_name=save_name,
                index=index,
                guitar_tab=guitar_tab
            )

        return JsonResponse({'message': '上传成功'}, status=200)


class MusicScoreListView(View):
    def get(self, request):
        queryset = GuitarTab.objects.all().order_by('-create_time')
        for obj in queryset:
            if not obj.cover_path:
                obj.cover_path = "https://img1.baidu.com/it/u=3622597983,3602987138&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=1200"
        # 获取当前页面的页码
        page = request.GET.get('page', 1)
        paginator = Paginator(queryset, 12)

        try:
            guitar_tabs = paginator.page(page)
        except PageNotAnInteger:
            guitar_tabs = paginator.page(1)
        except EmptyPage:
            guitar_tabs = paginator.page(paginator.num_pages)
        return render(request, 'guitar/MusicScoreList.html', {'guitar_tabs': guitar_tabs})


class MusicScoreDetailView(View):
    def get(self, request, id):
        guitar_tab = get_object_or_404(GuitarTab, id=id)

        # 获取所有关联的 GuitarTabImage
        images = guitar_tab.images.all()

        # 拼接图片的访问地址
        image_urls = []
        for image in images:
            image_url = Utils.get_guitar_url(image.save_name)
            image_urls.append({
                'url': image_url,
                'scroll_speed': image.scroll_speed,
                'rollback_to': image.rollback_to,
                'rollback_times': image.rollback_times,
            })

        context = {
            'guitar_tab': guitar_tab,
            'image_urls': image_urls,
        }

        return render(request, 'guitar/MusicScoreDisplay.html', context)


class SimpleGuitarTabView(View):
    def get(self, request, id):
        guitar_tab = get_object_or_404(GuitarTab, id=id)

        # 获取所有关联的 GuitarTabImage
        images = guitar_tab.images.all()

        # 拼接图片的访问地址
        image_urls = []
        for image in images:
            image_url = Utils.get_guitar_url(image.save_name)
            image_urls.append(image_url)

        context = {
            'guitar_tab': guitar_tab,
            'image_urls': image_urls,
        }

        return render(request, 'guitar/SimpleGuitarTabDisplay.html', context)
